package net.yxsoft.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.kit.Helper;
import net.yxsoft.kit.RSAKit;
import net.yxsoft.model.infrastructure.TsUser;
import net.yxsoft.resource.RetRes;
import net.yxsoft.service.common.BaseService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import rapid.core.Authuser;
import rapid.core.ContextStateEnum;
import rapid.core.TResult;
import rapid.util.StrKit;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class NodeAccountService extends BaseService {
    public static final NodeAccountService INSTANCE = new NodeAccountService();

    /**
     * @param name
     * @param account
     * @param password
     * @param groupId
     * @param roleIds
     * */
    public TResult createAccount(String name,String account,String password,String groupId,String roleIds,Authuser LogUser) {
        TsUser tsUser = new TsUser();
            tsUser.setLoginId(account);
            tsUser.setName(name);
            tsUser.setPassword(password);
            tsUser.setCanlogin("1");//允许登入
            tsUser.setStatus(1);//数据状态 启用
            tsUser.setEnabled("1");//数据状态 启用
        //平台新建账号
        TResult tResult = addUser(tsUser, LogUser);
        if(tResult.isFail()){
            return tResult;
        }
        TsUser newUser = TsUser.dao.findFirst("SELECT * FROM TS_USER WHERE LOGIN_ID=?", tsUser.getLoginId());
        try{

            //设置用户机构
            if(StringUtils.isNotBlank(groupId)){
                Record record = Db.findFirst("SELECT * FROM fn_form_data \n" +
                        "WHERE attrib_01=(SELECT id FROM fn_form WHERE code ='yyfwdygl')\n" +
                        "and attrib_37=(SELECT name FROM `ts_group` WHERE id = ? )", groupId);
                if(record==null){
                    newUser.delete();//之前平台保存的无用了，删除掉
                    return TResult.fail("无此应用单元服务");
                }
                String baseUrl = record.getStr("attrib_35");//接口标识符(服务的登入url)
                String serviceParam = record.getStr("ATTRIB_36");//登入信息json
                JsonNode loginJsonNode = mocExecPost(baseUrl, serviceParam, null); //调用登入接口获得登入认证token
                String token = loginJsonNode.get("data").get("token").asText();

                String addUserUrl = baseUrl.replace("login", "addUser");//修改成新增用户接口
                //调用应用单元远程接口创建应用单元账号
                JSONObject param = new JSONObject();
                param.put("name",account);
                param.put("pwd",password);
                param.put("role",0);
                JsonNode jsonNode = mocExecPost(addUserUrl, param.toString(), token);
                if(!"操作成功".equals(jsonNode.get("msg").asText())){
                    newUser.delete();//之前平台保存的无用了，删除掉
                    return TResult.fail("单元服务："+jsonNode.get("msg").asText());
                }
                //设置用户机构
                String[] gro = groupId.split(",");
                setUserGroupRelation(newUser.getId(), gro,LogUser);

            }else{
                newUser.delete();//之前平台保存的无用了，删除掉
                return TResult.fail("用户机构不能为空");
            }

            //设置用户角色
            if(StringUtils.isNotBlank(roleIds)){
                String[] roles = roleIds.split(",");
                setUserRoleRelation(newUser.getId(), roles,LogUser);
            }
        }catch (Exception e){
            e.printStackTrace();
            newUser.delete();//之前平台保存的无用了，删除掉
            return TResult.fail();
        }
        return TResult.success();
    };

    /**
     * 新增人员信息
     * @param: model
     * @param: sessionUser
     */
    public TResult addUser(TsUser model, Authuser sessionUser) {
        //判断当前添加的登录账号在系统中是否存在
        TsUser isExist = TsUser.dao.findFirst("SELECT * FROM TS_USER WHERE LOGIN_ID=?", model.getLoginId());
        if(model.getCardId() != null){
            List<TsUser> tsUserList  = TsUser.dao.find("SELECT * FROM TS_USER WHERE card_id=?",model.getCardId());
            if(tsUserList.size() > 0){
                return TResult.fail().msg("当前身份证号已存在");
            }
        }
        if(isExist != null) {
            //登录名已存在
            return TResult.fail().msg("用户名已存在");
        }
        String salt = model.getLoginId();
        String hashedPass = HashKit.sha256(salt + model.getPassword());

        model.setPassword(hashedPass);
        Timestamp time = new Timestamp(new java.util.Date().getTime());
        if(sessionUser!=null){
            model.setCreatorId(sessionUser.getId());
            model.setCreatorName(sessionUser.getName());
            model.setEditorId(sessionUser.getId());
            model.setEditorName(sessionUser.getName());
        }
        model.setCreateTime(time);
        model.setUpdateTime(time);
        model.setId(Helper.bulidUUID());
        Ret ret = RSAKit.generatorRSA();
        model.setRSAPrivateKey(ret.get(RetRes.PRIVATE_KEY).toString());
        model.setRSAPublicKey(ret.get(RetRes.PUBLIC_KEY).toString());

        boolean _r = model.save();
        if(_r) {
            //保存成功
            /*String strLog =  "主键：" + sessionUser.getId() + "，名称：" + sessionUser.getName() + "，新增用户名称：" + model.getName()  ;
            log(sessionUser.getLoginId(), sessionUser.getName(), "系统管理/用户管理", "新增", sessionUser.getLoginId(), strLog);*/
            return TResult.success();
        } else {
            //保存失败
            return TResult.fail().msg("保存失败");
        }
    }
    /**
     * 设置用户所属组织
     *  @param: userId
     *  @param: groupIds
     * @param: sessionUser
     */
    public TResult setUserGroupRelation(String userId, String[] groupIds,Authuser sessionUser) {
        String operation = "";
        TResult result = new TResult();
        List<String> _strsql = new ArrayList<String>();

        _strsql.add(String.format("DELETE FROM TS_UG_RELATION WHERE USER_ID='%s'", userId));

        if(groupIds != null && groupIds.length > 0) {
            for(String g : groupIds) {
                if(StrKit.hasValue(g)) {
                    _strsql.add(String.format("INSERT INTO TS_UG_RELATION(USER_ID,GROUP_ID) VALUES('%s','%s')", userId, g));
                }
            }
        }
        Db.batch(_strsql, 10000);
        if(sessionUser!=null){
            operation = "设置机构";
            String strLog = "主键：" + sessionUser.getId() + "，名称：" + sessionUser.getName()+ ",设置机构userId："+ userId + "，机构ID："+ groupIds;
            log(sessionUser.getLoginId(), sessionUser.getName(), "系统管理/用户管理", operation, sessionUser.getLoginId(),strLog);
        }
        result.setState(ContextStateEnum.SUCCESS);
        result.setMessage("机构保存成功.");
        return result;
    }

    /**
     * 设置用户所属角色
     *  @param: userId
     *  @param: roleIds
     * @param: sessionUser
     */
    public TResult setUserRoleRelation(String userId, String[] roleIds,Authuser sessionUser) {
        String operation = "";
        String str = "";
        TResult result = new TResult();
        List<String> _strsql = new ArrayList<String>();

        _strsql.add(String.format("DELETE FROM TS_UR_RELATION WHERE USER_ID='%s'", userId));

        if(roleIds != null && roleIds.length > 0) {
            for(String s : roleIds) {
                _strsql.add(String.format("INSERT INTO TS_UR_RELATION(USER_ID,ROLE_ID) VALUES('%s','%s')", userId, s));
                str += s + ",";
            }
        }
        Db.batch(_strsql, 10000);
        if(sessionUser!=null){
            operation = "设置角色";
            String strLog = "主键：" + sessionUser.getId() + "，名称：" + sessionUser.getName()+ ",设置角色userId："+ userId + "，角色ID："+ str;
            log(sessionUser.getLoginId(), sessionUser.getName(), "系统管理/用户管理", operation, sessionUser.getLoginId(),strLog);
        }
        result.setState(ContextStateEnum.SUCCESS);
        result.setMessage("角色保存成功.");
        return result;
    }

    /**
     * 服务与配置变更管理 执行Post请求
     *  url 请求地址
     *  param 请求参数
     *  jwtoken 认证信息
     * */
    public JsonNode mocExecPost(String url, String param, String jwtoken) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(5000) //连接超时时间
                        .setSocketTimeout(5000) //读取超时时间
                        .setConnectionRequestTimeout(5000) //请求超时时间
                        .build())
                .build();
        CloseableHttpResponse response = null;
        JsonNode jsonNode =null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("accept"," application/json");
            //认证不为空，则加上认证信息
            if(StringUtils.isNotBlank(jwtoken)){
                httpPost.setHeader("jwtoken",jwtoken);
            }
            // 创建参数列表
            if (param != null) {
                StringEntity postingString = new StringEntity(param, ContentType.APPLICATION_JSON);
                httpPost.setEntity(postingString);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            // 将字符串转换为JSON对象
            ObjectMapper objectMapper = new ObjectMapper();
            jsonNode = objectMapper.readValue(resultString, JsonNode.class);
            response.close();
        } catch (Exception e) {
            throw e;
        }
        return jsonNode;
    }


}
